package com.df.utils;

import com.df.script.IScript;

import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ClassLoadUtil {

    private static final Logger log = LoggerFactory.getLogger(ClassLoadUtil.class);

    public static <T> List<Class<T>> loadClass(String packageName, Class<T> clazz) {
        List<Class<T>> result = new ArrayList<>();
        if (StringUtil.isNullOrEmpty(packageName)) {
            log.error("加载包名为null或为空，加载失败！");
            return result;
        }

        String[] split = packageName.split("\\.");
        String loadPath = Arrays.asList(split).stream().reduce("/", (a, b) -> (a + "/" + b)).replaceFirst("/", "");

        System.out.println(loadPath);
//        System.out.println("类路径：" + Thread.currentThread().getClass().getResource("/"));
        URL resource = Thread.currentThread().getClass().getResource(loadPath);
        if (resource == null) {
            return result;
        }
        String path = resource.getPath();
        File loadDictional = new File(path);
        if (!loadDictional.exists()) {
            return result;
        }
        if (loadDictional.isFile()) {
            log.error("加载包名不是文件夹，加载失败！");
            return result;
        }

        File[] files = loadDictional.listFiles();
        for (File file : files) {
            String className = file.getName();
            if (file.isFile() && file.getName().endsWith(".class")) {
                className = file.getName().replace(".class", "");
                try {
                    Class<?> aClass = Class.forName(packageName + "." + className);
                    result.add((Class<T>) aClass);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                continue;
            }
            List<Class<IScript>> classes = loadClass(packageName + "." + className, IScript.class);
            for (Class<IScript> aClass : classes) {
                result.add((Class<T>) aClass);
            }
        }
        return result;
    }
}
